class Solution {
    public boolean exist(char[][] board, String word) {
     char []arr=word.toCharArray();
     for(int i=0;i<board.length;i++){
         for(int j=0;j<board[0].length;j++){
             //遍历board数组中的每个元素与字符数组先匹配
             if(dfs(board,arr,i,j,0)){
                 return true;
             }
         }
     }
     return false;
    }
    public boolean dfs(char[][] board ,char[] arr,int i,int j,int k){
        //数组越界，或者不匹配，返回false;
        if(i<0||i>=board.length||j<0||j>=board[0].length||board[i][j]!=arr[k]){
            return false;
        }
        if(k==arr.length-1){
            return true;
        }
        board[i][j]='\0';//避免重复查询
        boolean res= dfs(board,arr, i,j+1,k+1)
                ||dfs(board,arr,i,j-1,k+1)
                ||dfs(board,arr,i+1,j,k+1)
                ||dfs(board,arr,i-1,j,k+1);
        board[i][j]=arr[k];
        return res;
    }
}